package com.cwj.scalableIO.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author: Chenwujie
 * @date: 2021-07-20 16:28
 */
public class SingleReactor {
    private Selector selector;
    private ServerSocketChannel channel;

    public SingleReactor(int port) throws IOException {
        this.selector = Selector.open();
        this.channel = ServerSocketChannel.open();
        channel.socket().bind(new InetSocketAddress(port));
        channel.configureBlocking(false);
        SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_ACCEPT);
        selectionKey.attach(new Acceptor());

    }

    class Acceptor implements Runnable{

        @Override
        public void run() {
            try {
                SocketChannel c = channel.accept();
                if(c != null){
                    new Handler(selector, c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void start(){
        while(true){
            try {
                selector.select();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                dispatch(iterator.next());
            }
            selectionKeys.clear();
        }
    }

    public void dispatch(SelectionKey key){
        Runnable r = (Runnable)key.attachment();
        if(r != null){
            r.run();
        }
    }
    public static void main(String[] args) {
//        SingleReactor singleReactor = new SingleReactor(6667);

    }


}
